<?php

class Model_Role extends Model_Dec {

	const TABLE = "role";
	
	/**
	 * @var protected $id id value
	 * @method int get_id() get_id(void)
	 * @method void set_id() set_id(int $id)
	 */
	protected $id = 0;

	/**
	 * @var protected $name name value
	 * @method string get_name() get_name(void)
	 * @method void set_name() set_name(string $name) 
	 */
	protected $name;

	/**
	 * @var protected $description descrition value
	 * @method string get_description() get_description(void)
	 * @method void set_description() set_description(string $description) 
	 */
	protected $description;

	/**
	 * @return Model_Role
	 */
	public function __construct($id=0) {
		if(is_numeric($id)) {
			$db = DB::select("id", "name", "description")->from(self::TABLE)->where("id", "=", $id)->limit(1);
		} else {
			$db = DB::select("id", "name", "description")->from(self::TABLE)->where("name", "=", $id)->limit(1);
		}
		$db = $db->as_assoc()->execute();
		if($db->count()>0) {
			$this->load($db->current());
		}
	}

	public static function get_all($limit = false) {
		$db = DB::select("id", "name", "description")->from(self::TABLE)->as_object(__CLASS__);
		if ($limit)
			$db->limit($limit);
		$result = $db->execute();
		
		$return = array();
		foreach($result as $obj){
			$return[] = $obj;
		}
		return $return;
	}
	
	public static function get_all_as_array($limit = false) {
		$db = DB::select("id", "name", "description")->from(self::TABLE)->as_object(__CLASS__);
		if ($limit)
			$db->limit($limit);
		$result = $db->execute();
		
		$return = array();
		foreach($result as $obj){
			$return[$obj->get_id()] = $obj->get_name();
		}
		return $return;
	}

	private static function get_database_fields() {
		return array(
			'name' => __("Role_Name"),
			'description' => __("Role_Description"),
		);
	}
	
	public function validate() {
		$validateArray = array();
		foreach(self::get_database_fields() as $key=>$value){
			$validateArray[$key] = $this->get($key);
		}

		$validation = Validation::factory($validateArray)
				->rule('name','not_empty')
				->rule('name','max_length', array(':value', 32))
				->rule('description','not_empty')
				->rule('description','max_length', array(':value', 255));
		
		if($validation->check()) {
			return $validateArray;
		} else {
			throw new Validation_Exception('validation', $validation);
		}
	}
	
	public static function get_report() {
		return DB::select(
				"id"
				, "name"
				, "description"
				, array("id", "actions"))
		->from(self::TABLE)
		->order_by("id", "ASC");
	}
	
	public function remove() {
		if(0==$this->get_users()->count()) {
			parent::remove();
		} else {
			throw new Exception(__("There are users with this role."));
		}
	}
	
	public function get_users() {
		return DB::select()->from('user')
				->join('role_user')->on('user.id', '=', 'role_user.user_id')
				->where('role_user.role_id','=',$this->get_id())
				->as_object()->execute();
	}
	
} // End Role